import React, { useEffect, useState } from 'react';
import styles from './index.less';
import { Input, Space,Table, Radio, Divider,Checkbox ,Pagination,Menu,Switch,message,Modal, Button} from 'antd';
import { SettingOutlined, DownOutlined, UpOutlined } from '@ant-design/icons';
import { observer } from 'mobx-react-lite';
import useStore from '@/context/useStore';
import { useLocation } from 'umi';
import { IAllPageNumData, IAnswerParams, ISelectPageNumData, ISelectParams } from '@/utils/manageInterface';
import Tabels from '@/components/tabels/tabels';
import Editor from 'for-editor';
import {SwapOutlined} from '@ant-design/icons'

let toolbar: {
  h1: true, // h1
  h2: true, // h2
  h3: true, // h3
  h4: true, // h4
  img: true, // 图片
  link: true, // 链接
  code: true, // 代码块
  preview: true, // 预览
  expand: true, // 全屏
  /* v0.0.9 */
  undo: true, // 撤销
  redo: true, // 重做
  save: true, // 保存
  /* v0.2.3 */
  subfield: true, // 单双栏模式
}
const AnswerDetail: React.FC = () => {
  let { manage } = useStore();
  let locations = useLocation()
  let id = locations.search.split('=')[1]
  let [{...detailparams},setDetailParams]=useState<IAnswerParams>({
    pageNum:1,
    pageSize:10,
    isScort:1,
    answerId:id,
    status:0
  })
  let [modal1Visible, setModal1Visible] = useState(false);
  let [selectPageData, setSelectPageData] = useState<ISelectPageNumData[]>([]);
  let [replyContext, setReplyContext] = useState('');
  let [headI, setHeadI] = useState("");
  let [searchValue, setSearchValue] = useState("");
  let [modal3Visible, setModal3Visible] = useState(false);
  let [filteredValue, setFilteredValue] = useState([]);
  let [selectparams, setSelectParams] = useState<ISelectParams>({ pageNum: 1, pageSize: 10, isRight: 0, type: '', questionTitle: '' });
  // let [data, setData] = useState<IAnswerList[]>([]);
  let [alltabel, setAlltabel] = useState<IAllPageNumData[]>([]);
  let [flag, setFlag] = useState(false);
  let [isSort, setIsSort] = useState(true);
  let [sortStyle, setSortStyle] = useState(false);
  useEffect(() => {
    let flag = false;
    if (!flag) {
      manage.answerDetail(id);
      manage.answerList(detailparams)
    };
    
    return ()=>{flag=true}
  }, [])

 //设置精品切换
function isQuality(quality:number,id:string) {
  manage.answerDetailData = { ...manage.answerDetailData, quality: quality ? 0 : 1 }
  quality?message.warn({content:'取消精品成功',className:styles.message}):message.success({content:'设置精品成功',className:styles.messages})
}

//选择其他有 “正确答案” 的类似问题
function allBbatchUpdates() {
  setModal3Visible(true)
     async function ync() {
       setSelectPageData(await manage.selectAnswerList(selectparams));
     }
     ync()
  }
//复选框变化
  function onChangeFlag(id: string, i: number) {
    let ind = manage.answerListData.findIndex(item => item.replyId == id)
    console.log(id)
    let newitem = manage.answerListData.filter(item => item.replyId == id)[0]
    newitem={...newitem,shield:i ? 0 : 1}
    manage.answerListData.splice(ind, 1, newitem)
    if (i) {
      // message.info('取消屏蔽成功')
      message.warn({content:'取消屏蔽成功',className:styles.messages})
    } else {
      // message.info('屏蔽成功')
      message.success({content:'屏蔽成功',className:styles.message})
    }
  }
//撤销认证
function outapprove() {
  message.info('撤销认证失败，没有权限')
  }
//认证答案
function inapprove(){
  message.info('认证答案失败，没有权限')
}
  
 //弹框显示类似答案
 async function tosetModal3Visible(modal1Visible: boolean) {
  setSearchValue('')
  setModal3Visible(modal1Visible);
  let questionIdList = filteredValue.map(item => {
    return alltabel[item-1].answerId;
  })
  let res=await manage.replyRightAnswer({ questionIdList, replyContext })
  if (res.code === 200) {
    message.info('批量回复成功')
  } else {
    message.info('批量恢复失败')
  }
}
//弹框头部状态切换
function headChange(i:number) {
  if (i === 0) {
    setHeadI('')
    manage.selectAnswerList({...selectparams,type:''});
  } else if (i === 1) {
    setHeadI('0')
    manage.selectAnswerList({...selectparams,type:"0"});
  } else if (i === 2) {
    setHeadI('4')
    manage.selectAnswerList({...selectparams,type:"4"});
  } else if (i === 3) {
    setHeadI('1')
    manage.selectAnswerList({...selectparams,type:"1"});
  } else if (i === 4) {
    setHeadI('2')
    manage.selectAnswerList({...selectparams,type:"2"});
  } else if (i === 5) {
    setHeadI('3')
    manage.selectAnswerList({...selectparams,type:"3"});
  }
}

//搜索问题
function searchProblem(value: string) {
  setSearchValue(value)
  manage.selectAnswerList({...selectparams,questionTitle:value,type:headI});
}
//编辑回答问题
function handleChange(value:string) {
  setReplyContext(value)
}
 //只看正确答案，通过孙组件回调触发
 function changeanswer(e:boolean) {
  if (e) {
    manage.selectAnswerList({...selectparams,isRight:Number(e)});
  } else {
    manage.selectAnswerList({...selectparams,isRight:Number(e)});
  }
}
 //页码切换
 function pageChange(e:any) {
  manage.selectAnswerList({...selectparams,pageNum:e});
}
//回答
function batchUpdate() {
  setFlag(true)
}

//发布
  async function reply() {
    let res = await manage.reply({ questionValue: replyContext, answerId: id })
    manage.answerList(detailparams)
    if (res.code == 200) {
      message.info('回答成功')
      setReplyContext('')
  }

}
useEffect(()=>{
  manage.answerList({...detailparams,isScort:isSort?1:0})
},[isSort])
//排序
  function sort() {
  setSortStyle(true)
  setIsSort(!isSort)
}
  return <div>
    <div className={styles.answerhead}>
      <span style={{color:"#999"}}>问答</span> / <span>问答详情</span>
    </div>
    <div className={styles.answermain}>
      <div>
        <div className={styles.detail}>
                <p>{manage.answerDetailData?.quality?<img style={{width: "50px"}} src="http://111.203.59.61:8060/static/img/boutique.fc46be52.svg" />:''}<span>{manage.answerDetailData?.questionTitle}</span></p>
                <p><img style={{width: "35px",height:"35px",borderRadius:"50%"}} src={`http://111.203.59.61:8060${manage.answerDetailData.userPictureUrl}`} /><span>{manage.answerDetailData.userName}</span><span>发布于{manage.answerDetailData.pushTime}</span></p>
                <p>{manage.answerDetailData.questionContent}</p>
                {/* <p>{manage.answerDetailData.labels.map((ite:any, ind:any) => <span key={ind}>{ite}</span>)}</p> */}
              <div>
                <span onClick={batchUpdate}>回答</span>
                <span onClick={allBbatchUpdates}>选择其他有 “正确答案” 的类似问题</span>
                <span onClick={()=>isQuality(manage.answerDetailData?.quality,manage.answerDetailData.answerId)}>{manage.answerDetailData.quality?"取消精品":"设为精品"}</span>
              </div>
              <span><img style={{width: "20px",height:"20px"}} src="" alt="" />{manage.answerDetailData.answerCount}</span>
        </div>
      </div>
      {flag ? <div className={styles.editor}>
        <span onClick={reply}>发布</span>
        <Editor preview={true} subfield={true} height="360px" value={replyContext} onChange={(value) => handleChange(value)} toolbar={toolbar} />
      </div>:''}
      <div className={styles.list}>
            <h3><p><span>全部回答（<span>{manage.total}</span>）</span> <span>默认排行<i onClick={sort} className={sortStyle?styles.active:''}><SwapOutlined /></i></span></p></h3>
            {
              manage.answerListData!.map(item=>{
                return <li key={item.replyId}>
                    <p><img style={{width: "35px",height:"35px",borderRadius:"50%"}} src={`http://111.203.59.61:8060${item.userPictureUrl}`} /><span>{item.userName}</span><span>发布于{item.replyDate}</span></p>
                    <p>{item.replyContext}</p>
                    <div>
                      {item.authentication?<img src="http://111.203.59.61:8060/static/img/teacher_authentication.6b60f685.svg" alt=""/>:''}
                      {item.shield?<img src="http://111.203.59.61:8060/static/img/sheild.c2ae03f1.svg" alt=""/>:''}
                    </div>
                    <p>{item.authentication?<span onClick={outapprove} className={styles.span1}>撤销认证</span>:<span className={styles.span2} onClick={inapprove}>认证该答案</span>}<Switch defaultChecked={!!item.shield} onChange={()=>onChangeFlag(item.replyId,item.shield)}/></p>
                </li>
              })
            }
          </div>
          <Pagination defaultCurrent={1} total={manage.total||1} className={styles.pagination} showQuickJumper={true}/>
    </div>
    <Modal
              style={{height:"600px"}}
              title="选择其它有“正确答案”的类似问题"
              centered
              visible={modal3Visible}
              onOk={() => tosetModal3Visible(false)}
              onCancel={() => setModal3Visible(false)}
              cancelText="取消"
              okText="确定"
              width="70%"
              // wrapClassName={styles.title}
            >
          <Tabels headChange={headChange} searchProblem={searchProblem} selectPageData={selectPageData} total={manage.total||1} changeanswer={changeanswer} pageChange={pageChange}/>
    </Modal>   

  </div>
}

export default observer(AnswerDetail)